import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {PERMISSION} from './constants';
import routes from './routes';
import styles from './style.css';
import {Card, Table, Row, Collapse, Button, Spin, Form, Popconfirm, Col} from 'antd';
import {DATE_FORMAT, TABLE, FORM_ROW_OPTIONS} from '../constants';
import {formatDateTime, conventEnumValueToString, formatAmount, formatPercent} from '../utils';
import {saleOrderStatus} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import TextInput from 'Shared/components/TextInput';
import Return from '../common/Return';
const {Description} = DescriptionList;
const Panel = Collapse.Panel;
const FormItem = Form.Item;
export class ReturnOrder extends React.PureComponent {
    state = {
        loading: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleSubmitClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onChange = (name, value) => {
        if(!this.state.hasOperat)
            this.setState({hasOperat: true});
        this.props.onConditionsChange(name, value);
    }
    render() {
        const {details = []} = this.props.detail;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'returnOrder.colums.partCode',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'partCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'returnOrder.colums.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'returnOrder.colums.planQuantity',
                    defaultMessage: '订货数量'
                }),
                dataIndex: 'planQuantity'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'returnOrder.colums.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'returnOrder.colums.taxPrice',
                    defaultMessage: '含税价格'
                }),
                dataIndex: 'taxPrice',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'returnOrder.totalTaxPrice',
                    defaultMessage: '订货金额'
                }),
                dataIndex: 'totalTaxPrice',
                className: styles.textAlign,
                render: (text, record) => {
                    const {taxPrice = 0, planQuantity = 0} = record;
                    return formatAmount(taxPrice * planQuantity);
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'returnOrder.colums.minPackSize',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minPackSize'
            }
        ];
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Card
                        title={this.props.intl.formatMessage({
                            id: 'returnOrder.card.title',
                            defaultMessage: '退回信息'
                        })}>
                        <Row className="form-standard">
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'returnOrder.form.remark',
                                    defaultMessage: '备注'
                                })}
                                {...FORM_ROW_OPTIONS.item}>
                                <TextInput type="textarea" name="remark" value={this.props.remark} onBlur={this.onChange} />
                            </FormItem>
                        </Row>
                    </Card>
                    <Collapse bordered={false}>
                        <Panel header={<span className={styles.panelTitle}>{this.props.intl.formatMessage({
                            id: 'returnOrder.detail.panel',
                            defaultMessage: '申请单详情'
                        })}</span>} key="1" forceRender>
                            <Card>
                                <DescriptionList
                                    size="large"
                                    title={this.props.intl.formatMessage({
                                        id: 'returnOrder.panel.title',
                                        defaultMessage: '单据信息'
                                    })}>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.code',
                                            defaultMessage: '订单编号'
                                        })}>
                                        {this.props.detail.code}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.dealerName',
                                            defaultMessage: '总代名称'
                                        })}>
                                        {this.props.detail.dealerName}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.typeName',
                                            defaultMessage: '订单类型'
                                        })}>
                                        {this.props.detail.typeName}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.status',
                                            defaultMessage: '状态'
                                        })}>
                                        {conventEnumValueToString(saleOrderStatus, this.props.detail.status)}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.requiredArrivedDate',
                                            defaultMessage: '要求到货日期'
                                        })}>
                                        {formatDateTime(this.props.detail.requiredArrivedDate, DATE_FORMAT)}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.raisingRate',
                                            defaultMessage: '加价率'
                                        })}>
                                        {formatPercent(this.props.detail.raisingRate)}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.totalFee',
                                            defaultMessage: '总金额'
                                        })}>
                                        {formatAmount(this.props.detail.totalFee)}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.creditCode',
                                            defaultMessage: '销售凭证编号'
                                        })}>
                                        {this.props.detail.creditCode}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.creditDescribe',
                                            defaultMessage: '销售凭证描述'
                                        })}>
                                        {this.props.detail.creditDescribe}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.orderReasonCode',
                                            defaultMessage: '订购原因编号'
                                        })}>
                                        {this.props.detail.orderReasonCode}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.orderReason',
                                            defaultMessage: '订购原因描述'
                                        })}>
                                        {this.props.detail.orderReason}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'returnOrder.info.warehouseName',
                                            defaultMessage: '出库仓库'
                                        })}>
                                        {this.props.detail.warehouseName}
                                    </Description>
                                </DescriptionList>
                            </Card>
                            <Card
                                title={this.props.intl.formatMessage({
                                    id: 'returnOrder.details.title',
                                    defaultMessage: '清单'
                                })}
                                bordered={false}>
                                <Table
                                    className="white-space-nowrap"
                                    rowKey="id"
                                    columns={columns}
                                    pagination={false}
                                    dataSource={details}
                                    {...TABLE} />
                            </Card>
                        </Panel>
                    </Collapse>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
                {this.props.isSubmitable &&
                    <Card type="inner">
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit" loading={this.state.loading || this.props.loading}
                                    onClick={this.handleSubmitClick} className={styles.btnMargin} type="primary">{this.props.intl.formatMessage({
                                        id: 'returnOrder.btn.save',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                }
            </div>
        );
    }
}
ReturnOrder.propTypes = {
    detail: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    isSubmitable: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object,
    remark: PropTypes.string
};
import {connect} from 'react-redux';
import {getDetail, clearData, onClickReturnOrder, querySearch, saveSubmitCondition} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const EMPTY_ARRAY = [];
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const getRemark = selectorFactory(['page', 'appState', 'submitData', 'remark']);
const getSubmitable = createSelector(
    state => getPermissions(state),
    state => getDetailData(state),
    (permissions, detail) => {
        const {options = EMPTY_ARRAY} = detail;
        return permissions.includes(PERMISSION.return) && options.includes(PERMISSION.return);
    }
);
const mapStateToProps = state => ({
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    detail: getDetailData(state),
    remark: getRemark(state),
    isSubmitable: getSubmitable(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onClickSubmit: () =>
        dispatch(onClickReturnOrder(ownProps.id)).then(success => {
            if(success) {
                dispatch(querySearch());
                ownProps.history.push(routes.query.url());
            }

            return success;
        }),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(value, name)),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(ReturnOrder));
